package com.jandar.spider.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ESUtil {
    private static final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).callTimeout(60, TimeUnit.SECONDS).build();

    private static final AtomicInteger repeatCount = new AtomicInteger(0);
    private static final AtomicInteger exceptionCount = new AtomicInteger(0);


    public int getESRepeatCount() {
        Runnable runnable = () -> {
            Request request = new Request.Builder()
                    .url("http://172.16.137.12:1180/exkb/api/listIndex?indexes=jandar_locust_v1&page=1&size=15")
                    .addHeader("appKey", "jandar")
                    .addHeader("secret", "jandar")
                    .get().build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                JSONObject responseBody = JSONObject.parseObject(Objects.requireNonNull(response.body()).string());
                JSONArray data = responseBody.getJSONArray("data");
                int indexedCount = data.getJSONObject(0).getInteger("indexedCount");
                int docCount = data.getJSONObject(0).getInteger("docCount");
                repeatCount.set(indexedCount - docCount);
                exceptionCount.set(0);
            } catch (Exception e) {
                e.printStackTrace();
               if (exceptionCount.getAndIncrement()> 10) {
                   repeatCount.set(repeatCount.get()+1);
               }

            }
        };
        // 创建一个ExecutorService
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        // 提交Runnable任务给ExecutorService，并获取一个Future对象
        Future<?> future = executorService.submit(runnable);

        // 如果你想等待任务完成，可以调用future.get()，但这会阻塞当前线程
        // future.get();

        // 关闭ExecutorService
        executorService.shutdown();
        return repeatCount.get();
    }
}
